<template>
  <div class="flex w-full h-full justify-center">
    <Card class="w-1/3">
      <template #title>
        <div class="flex items-center justify-between">
          <span class="text-lg">个人信息</span>
          <Button @click="handleEdit" type="link" class="text-blue-400">
            <SquarePen />
          </Button>
        </div>
      </template>
      <div class="w-full flex flex-col gap-3">
        <Avatar :size="50"></Avatar>
        <ConfigForm 
          v-model:form="formRef"
          :configs="configs"
          v-model:value="params"
          labelAlign="left"
          :wrapper-col="{span:24}"
          :label-col="{flex:'90px'}"
        />
        <div class="flex w-full items-center justify-around">
          <Button v-if="!isDisabled" type="primary" @click="handleAction" >确定</Button>
          <Button v-if="!isDisabled" type="primary" ghost @click="handleCancel">取消</Button>
        </div>  
      </div>
    </Card>
  </div>
</template>
<script lang="ts" setup>
import ConfigForm from '@/components/blog-form/ConfigForm.vue';
import {Card, Button, Avatar, Input, message} from 'ant-design-vue';
import { computed, ref } from 'vue';
import { UserInfo } from '../models/userInfo';
import { useUserStore } from '@/store/userStore';
import { editUserInfoAPI } from '@/api/userApi';
import { SquarePen } from 'lucide-vue-next';
const userStore = useUserStore()
const isDisabled = ref(true)
const formRef = ref()
const configs = computed(()=>[
  {
    key:'username',
    label:'用户名',
    type:Input,
    attrs:{
      disabled:isDisabled.value,
    }
  },
  
  {
    key:'phone_number',
    label:'联系电话',
    type:Input,
    attrs:{
      disabled:isDisabled.value,
    }
  },
  {
    key:'',
    label:'个人签名',
    type:Input,
    attrs:{
      disabled:isDisabled.value,
    }
  },
  {
    key:'email',
    label:'邮箱',
    type:Input,
    attrs:{
      disabled:isDisabled.value,
    }
  },
])

const loading = ref(false)
const params = ref<UserInfo>(new UserInfo())
params.value.userName = userStore.userName
params.value.avatarUrl = userStore.avatarUrl
params.value.role = userStore.role

const handleEdit = () => {
  isDisabled.value = false
}
const handleAction = async ()=>{
  try {
    loading.value = true
    await formRef.value.validate()
    await editUserInfoAPI(params.value.params)
    userStore.handleInit() // 更新前端仓库 
    isDisabled.value = true
    message.success('编辑成功')
  } 
  catch(err){
    console.log(err)
  }
  finally{
    loading.value = false
  }
}

const handleCancel = () => {
  params.value.userName = userStore.userName
  params.value.avatarUrl = userStore.avatarUrl
  params.value.role = userStore.role
  isDisabled.value = true
}
</script>
<style lang="less">
  
</style>